package online.heycm.nacosconf.config;

import javax.annotation.PostConstruct;
import online.heycm.platform.nacos.NacosConfListener;
import online.heycm.platform.nacos.NacosConfPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @author heycm
 * @since 2023/11/8 21:14
 */
@Configuration
public class NacosConfig {

    @Autowired
    private NacosConfListener nacosConfListener;

    @Autowired
    private NacosConfPublisher nacosConfPublisher;

    /**
     * 监听 read 配置更新
     */
    @PostConstruct
    private void listen() {
        nacosConfListener.addListener("read", "DEFAULT_GROUP", this::publish);
    }

    /**
     * 推送配置到 write
     */
    private void publish(String config) {
        if (StringUtils.isEmpty(config)) {
            return;
        }
        nacosConfPublisher.publish("write", "DEFAULT_GROUP", config);
    }
}
